<template>
	<view class="content-box">
		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<view class="border-box">
					<image class="search-icon" src="/static/icon/search-icon2.svg" mode="aspectFit"></image>
					<input
						class="search-input"
						type="text"
						:placeholder="t('market.ss')"
						v-model="searchText"
						@input="handleSearchInput"
					/>
				</view>
			</view>
			<view class="search-txt" v-if="searchText" @click="goBack">{{t('common.cancel')}}</view>
		</view>
		
		<!-- 热搜列表 -->
		<view class="hot-search-section" v-show="!searchText">  <!-- hotSearchList.length -->
			<view class="section-title">{{ t('search.rs') }}</view>
			<view class="hot-list">
				<view class="hot-item" v-for="(item, index) in hotSearchList" :key="index" @click="selectCoin(item)">
					<view class="hot-item-left">
						<view class="hot-rank" :class="{'top-rank': index < 3}">{{ index + 1 }}</view>
						<view class="hot-name">{{ item.name }}</view>
						<view class="hot-pair">{{ item.pair }}</view>
						<image v-if="item.isHot" class="hot-icon" src="/static/icon/hot.svg" mode="aspectFit"></image>
					</view>
					<view class="hot-item-right">
						<view class="price">{{ item.price }}</view>
						<view class="change" :class="{'positive': item.change > 0, 'negative': item.change < 0}">
							{{ item.change > 0 ? '+' : '' }}{{ item.change }}%
						</view>
						<image 
							class="favorite-icon" 
							:src="`/static/icon/${item.isFavorite ? 'yishoucang' : 'weishoucang'}.svg`" 
							mode="aspectFit"
							@click.stop="toggleFavorite(index)"
						></image>
					</view>
				</view>
			</view>
		</view>
			<!-- 搜索结果列表 -->
		<view class="search-results" v-show="searchText && (searchResults.length > 0 || isSearching)">
			<!-- 加载状态 -->
			<view v-if="isSearching" class="loading-box">
				<text>搜索中...</text>
			</view>
			<!-- 搜索结果 -->
			<view class="result-list" v-else>
				<view class="result-item" v-for="(item, index) in searchResults" :key="index" @click="selectCoin(item)">
					<view class="item-left">
						<image class="coin-icon" :src="item.logo || `/static/icon/${item.name}.png`" mode="aspectFit"></image>
						<view class="coin-info">
							<text class="coin-name">{{ item.name }}</text>
							<text class="coin-pair">{{ item.pair }}</text>
						</view>
					</view>
					<view class="item-center">
						<text class="coin-price">{{ item.price }}</text>
					</view>
					<view class="item-right">
						<view class="change-btn" :class="{ positive: item.change > 0, negative: item.change < 0 }">
							<text class="change-text">{{ item.change > 0 ? '+' : '' }}{{ item.change }}%</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 无搜索结果 -->
		<view class="null-data" v-show="searchText && !isSearching && searchResults.length === 0">
			<image src="/static/icon/null-data.svg" class="icon"></image>
			<view class="text">{{ t('search.myssjg') }}</view>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { useI18n } from 'vue-i18n';
	import { goodsApi } from '@/utils/api.js';
	const { t } = useI18n();

	// 响应式数据
	const searchText = ref('');
	const searchResults = ref([]);
	const isSearching = ref(false);
	const searchCache = new Map(); // 关键词缓存
	const debounceTimer = ref(null); // 防抖定时器
	
	// 热搜列表数据
	const hotSearchList = ref([]);

	// 格式化产品代码
	const formatProductCode = (code) => {
		if (!code) return { name: 'N/A', pair: 'N/A' };
		const upperCode = String(code).toUpperCase();
		const baseCurrencies = ['USDT', 'USD', 'BTC', 'ETH', 'BNB'];
		for (const base of baseCurrencies) {
			if (upperCode.endsWith(base)) {
				const name = upperCode.replace(base, '');
				return { name, pair: `${name}/${base}` };
			}
		}
		if (upperCode.length > 4) {
			const name = upperCode.slice(0, -4);
			const base = upperCode.slice(-4);
			return { name, pair: `${name}/${base}` };
		}
		return { name: upperCode, pair: upperCode };
	};

	// 防抖搜索函数
	const debounce = (func, delay = 300) => {
		return function(...args) {
			clearTimeout(debounceTimer.value);
			debounceTimer.value = setTimeout(() => func.apply(this, args), delay);
		}
	};

	// 执行搜索
	const performSearch = async (keyword) => {
		if (!keyword || keyword.trim() === '') {
			searchResults.value = [];
			return;
		}

		const trimmedKeyword = keyword.trim();

		// 检查缓存
		if (searchCache.has(trimmedKeyword)) {
			searchResults.value = searchCache.get(trimmedKeyword);
			return;
		}

		try {
			isSearching.value = true;

			const response = await goodsApi.getStockPage({
				pageNo: 1,
				pageSize: 15,
				category: 9,
				keywords: trimmedKeyword
			});

			if (response?.code === 0 && response.data?.list) {
				// 处理数据
				const processedData = response.data.list.map(item => {
					const stockInfo = item.stockInfo || {};
					const market = stockInfo.market || {};
					const { name, pair } = formatProductCode(item.productCode);

					return {
						id: item.id,
						stockId: item.stockId,
						name: name,
						pair: pair,
						price: market.lastPrice || '0.00',
						change: parseFloat(String(market.changePercent || '0').replace('%', '')),
						logo: item.logo
					};
				});

				// 缓存结果
				searchCache.set(trimmedKeyword, processedData);
				searchResults.value = processedData;

				// 限制缓存大小（最多缓存50个关键词）
				if (searchCache.size > 50) {
					const firstKey = searchCache.keys().next().value;
					searchCache.delete(firstKey);
				}
			} else {
				searchResults.value = [];
			}
		} catch (error) {
			console.error('搜索失败:', error);
			searchResults.value = [];
		} finally {
			isSearching.value = false;
		}
	};

	// 防抖搜索
	const debouncedSearch = debounce((keyword) => {
		performSearch(keyword);
	}, 300);

	// 处理搜索输入
	const handleSearchInput = (e) => {
		const keyword = e.detail.value;
		searchText.value = keyword;

		// 每次输入都触发搜索（防抖处理）
		debouncedSearch(keyword);
	};
	
	// 切换收藏状态
	const toggleFavorite = (index) => {
		hotSearchList.value[index].isFavorite = !hotSearchList.value[index].isFavorite;
	};
	
	// 选择币种
	const selectCoin = (item) => {
		// 跳转到详情页
		const detailId = item.stockId || item.id;
		const iconPath = item.logo || `/static/icon/${item.name}.png`;
		uni.navigateTo({
			url: `/pages/market/details?id=${detailId}&iconPath=${encodeURIComponent(iconPath)}`
		});
	};
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 获取热搜数据
	const fetchHotSearchData = async () => {
		try {
			const response = await goodsApi.getStockPage({
				pageNo: 1,
				pageSize: 15,
				category: 9
			});

			if (response?.code === 0 && response.data?.list) {
				hotSearchList.value = response.data.list.map((item, index) => {
					const stockInfo = item.stockInfo || {};
					const market = stockInfo.market || {};
					const { name, pair } = formatProductCode(item.productCode);

					return {
						name: name,
						pair: pair,
						price: market.lastPrice || '0.00',
						change: parseFloat(String(market.changePercent || '0').replace('%', '')),
						isHot: index < 3, // 前3个标记为热门
						isFavorite: false
					};
				});
			}
		} catch (error) {
			console.error('获取热搜数据失败:', error);
		}
	};

	// 页面加载时获取热搜数据
	onMounted(() => {
		fetchHotSearchData();
	});
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #F5F6FA;
		padding-bottom: 100rpx;
		padding: 60rpx 41.81rpx;
		box-sizing: border-box;
		// 搜索框样式
		.search-container {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 41.86rpx;
		
			.search-box {
				width: 100%;
				display: flex;
				align-items: center;
				padding: 1px;
				box-sizing: border-box;
				border-radius: 1742.54rpx;
				background: linear-gradient(90deg, rgba(14, 194, 157, 1) 0%, rgba(88, 218, 221, 1) 35.42%, rgba(25, 162, 203, 1) 68.75%, rgba(2, 124, 217, 1) 100%);
		
				.border-box {
					width: 100%;
					display: flex;
					align-items: center;
					border-radius: 1742.54rpx;
					background-color: #Fff;
					padding: 19.19rpx 86.6rpx 19.19rpx 43.3rpx;
				}
		
				// margin-right: 33.14rpx;
			}
		
			.search-txt {
				display: flex;
				font-size: 31.4rpx;
				font-weight: 400;
				line-height: 45.46rpx;
				color: rgba(0, 0, 0, 1);
				flex-shrink: 0;
				margin-left: 20.93rpx;
			}
		}
		
		
		
		.search-icon {
			width: 30rpx;
			height: 30rpx;
			margin-right: 21.44rpx;
			opacity: 0.6;
		}
		
		.search-input {
			flex: 1;
			font-size: 28rpx;
			color: #333333;
			border: none;
			outline: none;
			background: transparent;
		
			&::placeholder {
				color: #999999;
			}
		}
		
		
		
		.null-data{
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			gap: 37.86rpx;
			margin-top: calc(50vh - 300rpx);
			.icon{
				width: 174.43rpx;
				height: 133.7rpx;
			}
			.text{
				font-size: 31.4rpx;
				font-weight: 400;
				color: #3D3E52;
			}
		}

		// 搜索结果列表样式
		.search-results {
			.loading-box {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 60rpx 0;
				color: #999;
				font-size: 28rpx;
			}

			.result-list {
				.result-item {
					display: flex;
					align-items: center;
					padding: 30rpx 0;
					border-bottom: 1px solid rgba(0, 0, 0, 0.05);

					.item-left {
						display: flex;
						align-items: center;
						flex: 2;

						.coin-icon {
							width: 60rpx;
							height: 60rpx;
							margin-right: 20rpx;
							border-radius: 50%;
						}

						.coin-info {
							display: flex;
							flex-direction: column;

							.coin-name {
								font-size: 28rpx;
								color: #333;
								font-weight: 500;
								margin-bottom: 8rpx;
							}

							.coin-pair {
								font-size: 24rpx;
								color: #999;
							}
						}
					}

					.item-center {
						flex: 1;
						text-align: right;

						.coin-price {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
						}
					}

					.item-right {
						flex: 1;
						display: flex;
						justify-content: flex-end;

						.change-btn {
							padding: 8rpx 20rpx;
							border-radius: 8rpx;
							min-width: 120rpx;
							text-align: center;

							.change-text {
								font-size: 24rpx;
								color: #fff;
							}

							&.positive {
								background: #00B464;
							}

							&.negative {
								background: #FF5722;
							}
						}
					}
				}
			}
		}
		// 热搜列表样式
		.hot-search-section {
			.section-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.hot-list {
				.hot-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx 0;
					border-bottom: 1px solid rgba(0, 0, 0, 0.05);
					
					.hot-item-left {
						display: flex;
						align-items: center;
						
						.hot-rank {
							width: 40rpx;
							font-size: 28rpx;
							color: #999999;
							text-align: center;
							
							&.top-rank {
								color: #FF5722;
								font-weight: bold;
							}
						}
						
						.hot-name {
							font-size: 28rpx;
							color: #333333;
							font-weight: 500;
							margin-left: 20rpx;
						}
						
						.hot-pair {
							font-size: 24rpx;
							color: #999999;
							margin-left: 10rpx;
							display: none; // 根据设计图隐藏
						}
						
						.hot-icon {
							width: 30rpx;
							height: 30rpx;
							margin-left: 10rpx;
						}
					}
					
					.hot-item-right {
						display: flex;
						align-items: center;
						
						.price {
							font-size: 28rpx;
							color: #333333;
							font-weight: 500;
							margin-right: 20rpx;
							text-align: right;
							min-width: 120rpx;
						}
						
						.change {
							font-size: 24rpx;
							min-width: 100rpx;
							text-align: right;
							
							&.positive {
								color: #00B464;
							}
							
							&.negative {
								color: #FF5722;
							}
						}
						
						.favorite-icon {
							width: 40rpx;
							height: 40rpx;
							margin-left: 20rpx;
						}
					}
				}
			}
		}
	}
</style>